<template>
    <div>
        <div class="add_wrap content">
            <div flex="main:justify" class="margin_bottom_20">
                <p>
                    上传人：<span>{{ formData.userName || '--' }}</span>
                </p>
                <div style="margin-top: 15px">
                    <!-- !!(formData.imgFileList||{}).length -->
                    <el-radio v-model="formData.isNoGroup" :disabled="true" :label="false" @change="formData.imgFileList = []">组上传</el-radio>
                    <el-radio v-model="formData.isNoGroup" :disabled="true" :label="true" @change="formData.imgFileList = []">单个上传</el-radio>
                </div>
                <p>
                    上传日期：<span>{{ parseTime(formData.createTime, '{y}年{m}月{d}日{h}时{i}分') || '--' }}</span>
                </p>
            </div>
            <div flex="main:center cross:center">
                <el-upload ref="elupload" action="#" accept=".mp4" :file-list="formData.imgFileList" list-type="picture-card" multiple :http-request="httpRequest">
                    <template slot="file" slot-scope="{ file }">
                        <video :src="file.url" width="100%" height="100%"></video>
                        <a class="el-upload-list__item-name">
                            <i class="el-icon-document"></i>
                            {{ file.name }}
                        </a>
                        <label class="el-upload-list__item-status-label">
                            <i class="el-icon-upload-success el-icon-check"></i>
                        </label>
                        <i class="el-icon-close"></i>
                        <i class="el-icon-close-tip"> 按 delete 键可删除 </i>
                        <!---->
                        <span class="el-upload-list__item-actions">
                            <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                                <i class="el-icon-zoom-in"></i>
                            </span>
                            <span class="el-upload-list__item-delete" @click="handleReOnRemove(file)">
                                <i class="el-icon-delete"></i>
                            </span>
                        </span>
                    </template>

                    <i class="el-icon-plus"></i>
                </el-upload>
                {{ formData.fileList }}
                {{ formData.imgFileList }}
                <div flex="" style="flex-wrap: wrap">
                    <div v-for="(item, index) in formData.fileList" :key="index" style="width: 32%; margin-right: 5px; min-width: 320px">
                        <!-- <p><span style="color:red">*</span> 照片名称：</p>
            <el-input v-model="item.title" size="mini" class="margin_bottom_10" placeholder="输入标题名称" />
            <p>照片描述：</p>
            <el-input v-model="item.remark" size="mini" type="textarea" placeholder="输入照片描述" :autosize="{ minRows: 6}" />

            <div>{{ item }}</div> -->
                        <avue-form v-model="item.form" :option="calcOption" />
                    </div>
                </div>
            </div>
        </div>
        <div class="footer" flex>
            <button class="flex_1" style="line-height: 40px" @click="handleCancel">取消</button>
            <button type="primary" style="line-height: 40px" class="flex_1" @click="submitForm">确定</button>
        </div>
        <el-image v-show="false" ref="elImage" :preview-src-list="srcList" :type-list="typeList" />
    </div>
</template>

<script>
    export default {
        data() {
            return {
                formData: {
                    imgFileList: [],
                    fileList: []
                },
                srcList: [],
                typeList: [],
                loadding: true,
                currentIndex: null,
                currentRow: {},
                imgUrlSrc: ''
            }
        },
        computed: {
            headers() {
                return {
                    Authorization: 'Bearer ' + this.token
                }
            }
        },
        watch: {
            '$route.query': {
                async handler(newVal) {
                    this.token = newVal.token || 'eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6ImE1ZjJmODUxLTUyZWMtNGZhNi1iYjM5LWFjY2FlNTI3NmU4YiJ9.PM-3A2b0o3x-QuxwuNZ6FbIEa3ncbgXIslPUvtkoZ6UUFVKh_1Y0fjIVbe2gPgsx0MF09ZKZsgWpHDd1MMVABA'
                    this.currentIndex = newVal.currentIndex
                    this.loadding = true
                    this.currentRow = (await this.getDetailByNoticeId()).data
                    console.log('currentRow:', this.currentRow)
                    if (this.currentIndex || this.currentIndex === 0) {
                        this.formData = JSON.parse(this.currentRow.jsonStr)[this.currentIndex]
                        console.log(this.formData)
                        this.formData.imgFileList = this.formData.fileList.map(item => {
                            return {
                                name: 123,
                                url: item.fileUrl
                            }
                        })
                    } else {
                        this.initForm()
                    }
                    this.loadding = false
                },
                immediate: true
            }
        },
        async onLoad(option) {
            console.log('option: ', option);
            this.token = option.token || 'eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6ImE1ZjJmODUxLTUyZWMtNGZhNi1iYjM5LWFjY2FlNTI3NmU4YiJ9.PM-3A2b0o3x-QuxwuNZ6FbIEa3ncbgXIslPUvtkoZ6UUFVKh_1Y0fjIVbe2gPgsx0MF09ZKZsgWpHDd1MMVABA'
            this.currentIndex = option.currentIndex
            this.loadding = true
            this.currentRow = (await this.getDetailByNoticeId()).data
            console.log('currentRow:', this.currentRow)
            if (this.currentIndex || this.currentIndex === 0) {
                this.formData = JSON.parse(this.currentRow.jsonStr)[this.currentIndex]
                console.log(this.formData)
                this.formData.imgFileList = this.formData.fileList.map(item => {
                    return {
                        name: 123,
                        url: item.fileUrl
                    }
                })
            } else {
                this.initForm()
            }
            this.loadding = false
        },
        methods: {
            gettime(video, size) {
                console.log('123')
                const promise = new Promise(resolve => {
                    video.addEventListener('canplaythrough', e => {
                        console.log(58, e, e.target.duration)
                        // if (e.target.duration <= size) {
                        resolve(e.target.duration)
                        // } else {
                        //     resolve(false)
                        // }
                    })
                })
                return promise
            },
            async httpRequest(param) {
                console.log('上传', param)
                const uid = this.$refs.elupload.uploadFiles.slice(-1)[0].uid

                const file = param.file
                const url = window.URL || window.webkitURL

                const video = document.createElement('video')
                if (this.imgUrlSrc) {
                    url.revokeObjectURL(this.imgUrlSrc)
                }
                this.imgUrlSrc = url.createObjectURL(file)
                video.src = this.imgUrlSrc
                // video.src = 'file://storage/emulated/0/享做笔记/DCIM/Camera/123.mp4';
                console.log(video.src)
                let time = await this.gettime(video)
                console.log(time)
                this.formData.fileList.push({ ...param, uid, fileUrl: video.src })
                console.log(    this.formData.fileList);
                // video.addEventListener('loadeddata', () => {
                //     console.log('loadeddata')
                //     this.formData.fileList.push({ ...param, uid, fileUrl: video.src })
                // })
                // video.addEventListener('', e => {
                //     console.log('error')
                //     // 加载失败回收
                //     URL.revokeObjectURL(file)
                // })
            },
            handlePictureCardPreview(file) {
                console.log('handlePictureCardPreview', file)
                this.srcList = [file.url]
                this.typeList = [{ url: file.url, type: 'video' }]
                this.$refs.elImage.showViewer = true
            },
            // 调用el -upload 里子组件的方法，自动触发 handleOnRemove 方法
            handleReOnRemove(file) {
                var number = ''
                this.$refs.elupload.uploadFiles.forEach((v, i) => {
                    v.uid == file.uid ? (number = i) : ''
                })

                this.$refs.elupload.uploadFiles.splice(number, 1)
                // this.formData.imgFileList.splice(number, 1);
                this.formData.fileList.splice(number, 1)

                // this.$refs.elupload.$children[0].$emit("remove", file);
            },
            async getDetailByNoticeId() {
                return await fetch(`${this.baseUrl}/archives/notice/${this.$route.query.noticeId}`, {
                    method: 'GET',
                    headers: this.headers
                }).then(e => e.json())
            },
            async submitForm() {
                this.loadding = true
                let { jsonStr } = this.currentRow
                jsonStr = jsonStr && jsonStr != '' ? JSON.parse(jsonStr) : []
                this.formData.createTime = new Date().getTime()
                if (this.currentIndex) {
                    this.currentRow.handleType = 2
                    jsonStr.splice(this.currentIndex, 1, this.formData)
                } else {
                    this.currentRow.handleType = 1
                    jsonStr.push(this.formData)
                }
                // this.currentIndex ? jsonStr.splice(this.currentIndex, 1, this.formData) : jsonStr.push(this.formData)
                ;(this.currentRow.jsonStr = JSON.stringify(jsonStr)),
                    fetch(`${this.baseUrl}/archives/notice`, {
                        method: 'PUT',
                        headers: { ...this.headers, 'Content-Type': 'application/json;charset=UTF-8' },
                        mode: 'cors',
                        body: JSON.stringify(this.currentRow)
                    })
                        .then(e => e.json())
                        .then(res => {
                            if (res.code == 200) {
                                // alert(res.msg)
                                this.initForm()
                                this.loadding = false
                                this.backUniApp('success')
                                if (this.isMobile) {
                                    // this.$message.success('操作成功')
                                    alert('操作成功')
                                }
                                window.parent.postMessage('success', '*')
                            }
                        })
                        .catch(e => {
                            this.loadding = false
                            window.parent.postMessage('error', '*')
                        })
            },
            handleCancel() {
                this.initForm()
                uni.navigateBack()
                return
                this.backUniApp('cancel')
                window.parent.postMessage('cancel', '*')
                // window.history.go(-1)
            },
            initForm() {
                this.formData = {
                    imgFileList: [],
                    fileList: [],
                    userName: this.$route.query.nickName || '群众',
                    createTime: '',
                    title: `${this.$route.query.nickName || '群众'}-${this.parseTime(new Date(), '{y}年{m}月{d}日')}`
                }
            }
        }
    }
</script>

<style lang="scss" scoped>
    .content {
        height: calc(100vh - 66px);
        overflow: auto;
        align-items: flex-start;
        padding: 0 20px;
    }
</style>
